package controllers

import (
	"classOne/models"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"time"
)

type RegisterController struct {
	beego.Controller
}

func (this *RegisterController) ShowReg() {
	this.TplName = "register.html"

}

/**

 */

func (this *RegisterController) HandleReg() {
	username := this.GetString("username")
	password := this.GetString("password")
	beego.Info(username, password)
	//数据处理
	if username == "" || password == "" {
		beego.Info("用户名或密码不能为空")
		this.TplName = "register.html"
		return
	}
	//插入数据库
	//1.获取orm对象
	o := orm.NewOrm()

	//2.获取插入对象
	user := models.User{}
	//3.插入操作
	user.UserName = username
	user.Passwd = password

	_, err := o.Insert(&user)
	if err != nil {
		beego.Info("插入数据失败", err)
	}
	//4.返回登录
	this.Redirect("/", 302)
	// this.Ctx.WriteString("注册成功")
	// this.TplName = "login.html"
}

type LoginController struct {
	beego.Controller
}

func (this *LoginController) ShowLogin() {
	name := this.Ctx.GetCookie("userName")

	if name != "" {
		this.Data["userName"] = name
	}

	this.TplName = "login.html"
}

func (this *LoginController) HandleLogin() {
	userName := this.GetString("userName")
	password := this.GetString("password")
	if userName == "" || password == "" {
		beego.Info("用户名或密码不能为空")
		this.TplName = "login.html"
		return
	}

	//查找数据
	o := orm.NewOrm()
	//获取查询对象
	user := models.User{}
	user.UserName = userName

	err := o.Read(&user, "UserName")
	if err != nil {
		beego.Info("查询用户名失败")
		this.TplName = "login.html"
		return
	}
	if user.Passwd != password {
		beego.Info("密码失败")
		this.TplName = "login.html"
		return
	}

	remember := this.GetString("remember")
	beego.Info("记住密码", remember)
	if remember == "on" {
		this.Ctx.SetCookie("userName", userName, time.Second*3600)
	} else {
		this.Ctx.SetCookie("userName", "sss", -1)
	}

	this.SetSession("userName", userName)

	//4.返回视图
	this.Ctx.WriteString("登录成功")

}
